package com.atguigu.lease.web.app.service.impl;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constans.RedisConstant;
import com.atguigu.lease.common.excetion.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtils;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.rmi.dgc.Lease;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    //短信依赖的接口
    @Autowired
    private Client client;

    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");

    @Override
    public void loginCaptcha(String phone) throws Exception {
        //判断_是否是正常的手机号
        if (!PHONE_PATTERN.matcher(phone).matches()){
            throw  new LeaseException(ResultCodeEnum.DATA_ERROR,"手机号格式不正确");
        }

        //判断_验证码是否发送过,就是看redis里面是否有验证码这个值
        String value = (String)redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + phone);
        if (value != null){
            throw  new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }

        //验证码生成
        Random random = new Random();
        int captcha = 100000+random.nextInt(900000);

        //key:captcha 存储在redis
        redisTemplate.opsForValue().set(RedisConstant.APP_LOGIN_PREFIX + phone,
                String.valueOf(captcha),RedisConstant.APP_LOGIN_CODE_TTL_SEC,TimeUnit.SECONDS);

        //发送验证码,调用SMS服务 (手机号+签名+模版编号和模板参数 )
        SendSmsRequest sms = new SendSmsRequest();
        sms.setPhoneNumbers(phone);
        sms.setSignName("阿里云短信测试");
        sms.setTemplateCode("SMS_154950909");
        sms.setTemplateParam("{\"code\":\"" + captcha + "\"}\n");
        client.sendSms(sms);
    }

    @Override
    public String login(LoginVo vo) {
        //判断验证码是否为空
        if (ObjectUtils.isEmpty(vo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //判断验证码是否正确
        String value = (String)redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX+vo.getPhone());
        if (!vo.getCode().equals( value)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //判断手机号是否为空
        LambdaQueryWrapper<UserInfo> wrapper_phone = new LambdaQueryWrapper<>();
        wrapper_phone.eq(UserInfo::getPhone,vo.getPhone());
        UserInfo userInfo = userInfoService.getOne(wrapper_phone);
        if (userInfo == null){
            UserInfo user = new UserInfo();
            user.setPhone(vo.getPhone());
            user.setNickname("起名字"+vo.getPhone().substring(vo.getPhone().length()-4,vo.getPhone().length()));
            user.setAvatarUrl("https://tse4.mm.bing.net/th/id/OIP.iBy7zllJXvjrzOH-VdwH_gHaEK?cb=ucfimgc2&rs=1&pid=ImgDetMain&o=7&rm=3");
            user.setStatus(BaseStatus.ENABLE);
            userInfoService.save(user);
        }
        //这里是重新赋值 作用域不同
        userInfo = userInfoService.getOne(wrapper_phone);

        //判断账户是否被禁用
        if (BaseStatus.DISABLE==userInfo.getStatus()){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        //创建token
        String token = JwtUtils.createToken(userInfo.getId(), userInfo.getPhone());
        return token;
    }
}
